from PyQt4.QtGui import *
from PyQt4.QtCore import *

import boqdoc
import gui

def parent():
   '''Returns the main window to use as the parent argument is dialog functions.'''
   return gui.Manager().mainwindow
   
   
class Variable(object):
   def __init__(self, default, doc='', write=True):
      self.__value = default
      self.__doc__ = doc
      self.__write = write

   def __get__(self, instance, owner):
      return self.__value

   def __set__(self, instance, value):
      if self.__write:
         self.__value = value
      else:
         raise AttributeError, 'Cannot write to constant'


class Msg(object):
   '''Contains standard dialogs'''

   __instance = None
   __parent = None

   quiet = Variable(False, 'Suppress display of messages')
   yes   = Variable(QMessageBox.Yes)
   no    = Variable(QMessageBox.No)

   def __new__(cls):
      if cls.__instance is None:
         cls.__instance = object.__new__(cls)
      return cls.__instance

   def AreYouSure(self, message, default=None, show=False):
      '''Display a query dialog with Yes and No buttons.'''
      if show or not self.quiet:
         return self.yes == QMessageBox(parent(), 'Confirmation', message, self.yes, self.no)
      else:
         return default if default is not None else self.no

   def Error(self, message, show=False):
      '''Display an error dialog.'''
      if show or not quiet:
         QMessageBox.warning(parent(), 'Error', message, QMessageBox.Ok)

   def TextQuery(self, caption, default=''):
      '''Display a text entry box with default text. The text entered is returned,
      or None if the dialog is cancelled'''
      dialog = QTextEntryDialog(parent(), caption, 'boq', default)
      return dialog.GetValue() if dialog.showModal() == wx.CANCEL else None

   def About(self):
      '''Display an about box.'''
      QMessageBox.about(parent(), 'boq', 'BOQ')
      
      
def getColumnInterface():
   '''Displays a list of options for the column interface and returns the selected one.'''
   interfaces = {}
   for o in boqdoc.__dict__.itervalues():
      if isinstance(o, type) and issubclass(o, boqdoc.Interface):
         interfaces[str(o())] = o
   assert len(interfaces) > 0
   selected = QInputDialog.getItem(parent(), 'Select column type', 'Select column type', interfaces.keys(), 0, False)
   if selected[1]:
      return interfaces[str(selected[0])]
   else:
      return None


